package com.lan.app.api;

import com.lan.app.utils.Deploy;
import com.lan.support.response.json.R;
import com.lan.ScriptCompiler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.InputStream;

@Controller
@RequestMapping("api/lan")
public class LanApi {


    @ResponseBody
    @RequestMapping(value = "exec")
    public R add(@RequestParam String body) {
        ScriptCompiler compiler = new ScriptCompiler();
        Object result = compiler.compile(body);
        return R.OK(result);
    }


    @ResponseBody
    @RequestMapping(value = "deploy")
    public R deploy(@RequestParam String body) {
        Deploy.getInstance().compile(body);
        return R.OK();
    }

    @ResponseBody
    @RequestMapping(value = "isDeploy")
    public R isDeploy(boolean bool) {
        Deploy.getInstance().setDeploy(bool);
        return R.OK();
    }


    @ResponseBody
    @RequestMapping(value = "test")
    public R test() throws IOException {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("script/03.jsl");
        String body = read(is);
        ScriptCompiler compiler = new ScriptCompiler();
        Object result = compiler.compile(body);
        return R.OK(result);
    }

    private String read(InputStream is) throws IOException {
        StringBuilder sb = new StringBuilder();
        byte buffer[] = new byte[1024];
        int n = -1;
        while ((n = is.read(buffer, 0, 1024)) != -1) {
            sb.append(new String(buffer, 0, n, "UTF-8"));
        }
        return sb.toString();
    }


}
